package com.logica.tutorial.web;

import java.io.IOException;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.WebSocketRequestHandler;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.protocol.ws.api.IWebSocketConnection;
import org.apache.wicket.protocol.ws.api.SimpleWebSocketConnectionRegistry;
import org.apache.wicket.protocol.ws.api.WebSocketBehavior;
import org.apache.wicket.protocol.ws.api.message.ClosedMessage;
import org.apache.wicket.protocol.ws.api.message.ConnectedMessage;
import org.apache.wicket.protocol.ws.api.message.TextMessage;

public class GamePanel extends Panel {

	public GamePanel(String id) {
		super(id);

		add(new AjaxLink<Void>("changeColorLink") {
			@Override
			public void onClick(AjaxRequestTarget target) {
				String sessionId = getSession().getId();
				Integer pageId = Integer.parseInt(getPage().getId());
				SimpleWebSocketConnectionRegistry registry = new SimpleWebSocketConnectionRegistry();
				IWebSocketConnection connection = registry.getConnection(
						getApplication(), sessionId, pageId);
				if (connection != null) {
					try {
						connection.sendMessage("changeColor");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});

		add(new WebSocketBehavior() {
			private static final long serialVersionUID = 4654183593382814950L;

			@Override
			protected void onMessage(WebSocketRequestHandler handler,
					TextMessage message) {
				System.out.println("I got: " + message.getText());
				handler.push("Response.");
			}

			@Override
			protected void onConnect(ConnectedMessage message) {
				System.out.println("Connected.");
				SimpleWebSocketConnectionRegistry registry = new SimpleWebSocketConnectionRegistry();
				/* Could save info about different client connections: */
				IWebSocketConnection connection = registry.getConnection(
						message.getApplication(), message.getSessionId(),
						message.getPageId());

				try {
					connection.sendMessage("Message from server to client.");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			protected void onClose(ClosedMessage message) {
				System.out.println("Closed.");
			}
		});
	}

}
